package com.tangyuan.live.task;

import cn.hutool.core.util.StrUtil;
import com.tangyuan.common.result.Result;
import com.tangyuan.live.entity.enums.LiveRoomStatusEnum;
import com.tangyuan.live.entity.vo.EndLiveVo;
import com.tangyuan.live.service.LiveGroupService;
import com.tangyuan.live.service.LiveRoomService;
import com.tangyuan.live.util.LiveUtil;
import com.tangyuan.model.live.LiveRoom;
import com.tencentcloudapi.live.v20180801.models.StreamName;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TimedTask {

    @Autowired
    LiveUtil liveUtil;
    @Autowired
    LiveRoomService liveRoomService;
    @Autowired
    LiveGroupService liveGroupService;


    /**
     * 定时任务：关闭断流的直播
     * 该方法主要逻辑为：
     * 1. 获取未关闭的直播最晚时间
     * 2. 根据时间获取推流数据
     * 3. 迭代推流数据，记录每个直播流的最早结束时间
     * 4. 查询未关闭的直播房间
     * 5. 检查直播房间是否断流超过十分钟，如果是，则关闭直播
     */
   // @Scheduled(cron = "0 0/1 * * * ?")
    @XxlJob("closeCutoffLive")
    public void closeCutoffLive() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date closeLiveTime = liveGroupService.getMaxNoCloseLiveTime();
        if(closeLiveTime == null){
            log.info("没有未停止的直播");
            return;
        }
        StreamName[] name = liveUtil.getStreamName(closeLiveTime);
        if(name == null || name.length < 1){
            log.info("没有获取到推流数据");
            return;
        }
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < name.length; i++) {
            StreamName streamName = name[i];
            try {
                Long.parseLong(streamName.getStreamName());
            } catch (NumberFormatException e) {
                log.info("直播流错误,流名称:{}",streamName.getStreamName());
                continue;
            }
            String startTime = map.get(streamName.getStreamName());
            if(StrUtil.isEmpty(startTime)){
                startTime = streamName.getStreamEndTime();
            }else {
                boolean b = format.parse(startTime).compareTo(format.parse(streamName.getStreamEndTime())) > 0;
                startTime = b ? streamName.getStreamEndTime() : startTime;
            }
            map.put(streamName.getStreamName(),startTime);
        }
        List<Long> ids = map.keySet().stream().map(Long::parseLong).collect(Collectors.toList());
        List<LiveRoom> byIds = liveRoomService.getNoCloseLiveByUserIds(ids, LiveRoomStatusEnum.UNDERWAY.status);
        //断流的直播群组
        List<String> list = new ArrayList<>();
        for (LiveRoom liveRoom : byIds) {
            if(liveRoom.getStatus().equals(LiveRoomStatusEnum.UNDERWAY.status)){
                String s = map.get(liveRoom.getUserId().toString());
                long cutoffTime = format.parse(s).getTime();
                long currentTime = new Date().getTime();
                //断流超过十分钟,结束直播
                if(currentTime - cutoffTime > 1000*60*10){
                    list.add(liveRoom.getGroupId());
                    Result<EndLiveVo> result = liveRoomService.endLive(liveRoom.getUserId(), liveRoom.getId());
                    if(!result.isOk()){
                        log.error("定时结束断流直播失败,直播间:{},错误码:{},错误原因:{}",liveRoom.getId(),result.getCode(),result.getMessage());
                    }else {
                        log.info("定时结束断流直播成功,直播间:{}",liveRoom.getId());
                    }
                }
            }
        }
        liveGroupService.setCutoffLive(list);
    }

}
